package avicit.im.lantop.employeeshortcutkeys.action;


import avicit.im.lantop.employeeshortcutkeys.domain.EmployeeShortcutKeys;
import avicit.im.lantop.employeeshortcutkeys.service.EmployeeshortcutService;
import avicit.im.lantop.employeeshortcutkeys.service.api.EmployeeshortcutServiceApi;
import avicit.platform6.api.session.SessionHelper;
import avicit.platform6.core.context.ThreadContextHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employeeshortcutController")
@SuppressWarnings("deprecation")
public class EmployeeshortcutController {
    @Autowired
    private EmployeeshortcutServiceApi employeeshortcutService;

    /**
     * 获取所有的快捷键设置
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getEmpItem")
    @ResponseBody
    public List<Map<String, Object>> getEmpItem(HttpServletRequest request)throws  Exception{
        List<Map<String, Object>> mapList = employeeshortcutService.getEmpItem();
        return  mapList;
    }

    /**
     * 根据Id 获取快捷键内容
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getEmpItemById")
    @ResponseBody
    public Map<String,Object> getEmpItemById(HttpServletRequest request)throws  Exception{
        String id=request.getParameter("id");
        Map<String,Object> map = new HashMap<>();
        EmployeeShortcutKeys em = employeeshortcutService.getEmpItemById(id);
        if(null!=em){
            map.put("id",em.getID());
            map.put("shortcutKeyName",em.getShortcutKeyName());
            map.put("linkAddress",em.getLinkAddress());
            map.put("SHORTCUT_KEY_PICTURE",em.getShortcutKeyPicture());
            map.put("flag","1");
        }else{
            map.put("flag","0");
        }
        return  map;
    }

    /**
     * 更新快捷键
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping( value = {"/uploadPicture"},method = {RequestMethod.POST})
    public Map<String,Object> uploadPicture(HttpServletRequest request) throws IOException {
    	  String id=request.getParameter("id");
          String shortcutKeyName=request.getParameter("shortcutKeyName");
          String linkAddress=request.getParameter("linkAddress");
          String SHORTCUT_KEY_PICTURE=request.getParameter("SHORTCUT_KEY_PICTURE");
          Map<String,Object> map = new HashMap<>();
          //SanXia delete by An start以流的形式存储在数据库
//        if (request instanceof MultipartHttpServletRequest) {
//            MultipartHttpServletRequest murequest = (MultipartHttpServletRequest)request;
//            multipartFile = murequest.getFile("SHORTCUT_KEY_PICTURE");
//        }
        try {
//            String imgName = id+".jpg";
//            String imgpath="avicit/im/lantop/employeeshortcutkeys/imgs/";
//            String path = request.getSession().getServletContext().getRealPath(imgpath);
//            File filePath=new File(path);
//            if (!filePath.exists()) {
//                filePath.mkdirs();
//            }
//            File file = new File(path + "\\"+imgName);
//            FileOutputStream os = new FileOutputStream(file);
//            InputStream ins = multipartFile.getInputStream();
//            int bytesRead = 0;
//            byte[] buffer = new byte[8192];
//            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
//                os.write(buffer, 0, bytesRead);
//            }
//            os.close();
//            ins.close();
//            mav.put("path",1);
        	 //SanXia delete by An end
            String orgId = ThreadContextHelper.getOrgId();
            EmployeeShortcutKeys em=new EmployeeShortcutKeys();
            em.setID(id);
            em.setOrgId(orgId);
            em.setSysId("LANTOP");
            em.setLinkAddress(linkAddress);
            em.setShortcutKeyName(shortcutKeyName);
            em.setShortcutKeyPicture(SHORTCUT_KEY_PICTURE);
            employeeshortcutService.updateEmpItemById(em);
            map.put("flag","1");
        }
        catch (Exception e){
            e.printStackTrace();
            map.put("flag","0");
        }
        return  map;
    }
    
    /**
     * 获取所有的快捷键设置
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getEmp")
    @ResponseBody
    public List<Map<String, Object>> getEmp(HttpServletRequest request)throws  Exception{
        List<Map<String, Object>> mapList=employeeshortcutService.getEmp();
        return  mapList;
    }

    /**
     * 上传图片
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping( value = {"/uploadPictureNew"},method = {RequestMethod.POST})
    public ModelAndView uploadPictureNew(HttpServletRequest request, HttpServletResponse response)throws Exception{
        ModelAndView mav = new ModelAndView("avicit/im/lantop/employeeshortcutkeys/jsp/employeePictureUpload");
         MultipartFile multipartFile = null;
        mav.addObject("flag", "1");
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest murequest = (MultipartHttpServletRequest)request;
            multipartFile = murequest.getFile("file");
        }
        if(null==multipartFile){
            return mav.addObject("message", "上传失败！");
        }
        try {

            String imgpath="avicit/im/lantop/employeeshortcutkeys/imgs/";
            String Suffix=multipartFile.getOriginalFilename().substring((multipartFile.getOriginalFilename().length())-4,(multipartFile.getOriginalFilename().length()));
            String path = request.getSession().getServletContext().getRealPath(imgpath);
            File filePath=new File(path);
            File[] files = filePath.listFiles();
            String imgName=(Integer.valueOf(files.length))+1+Suffix;
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            File file = new File(path + "\\"+imgName);
            FileOutputStream os = new FileOutputStream(file);
            InputStream ins = multipartFile.getInputStream();
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        }
        catch (Exception e){
            e.printStackTrace();
            return mav.addObject("message", "上传失败！");
        }
        return mav.addObject("message", "上传成功！");
    }

    /**
     * 获取图片
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getPic")
    @ResponseBody
    public List<Map<String, Object>> getPic(HttpServletRequest request)throws  Exception{
        String imgpath="avicit/im/lantop/employeeshortcutkeys/imgs/";
        String path = request.getSession().getServletContext().getRealPath(imgpath);
        File file = new File(path);
        List<Map<String, Object>> list=new ArrayList<>();
        // 如果这个路径是文件夹
        if (file.isDirectory()) {
            // 获取路径下的所有文件
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                Map<String ,Object> map=new HashMap<>();
                String  imgName= (files.length-i)+".png";
                String picAddr=imgpath+imgName;
                map.put("imgName",imgName);
                map.put("picAddr",picAddr);
                list.add(map);
            }
        }
        return list;
    }

}
